<template>
  <div class="interview-answer-page">
    <a-card :bordered="false">
      <!-- 页面头部 -->
      <div class="page-header">
        <a-space>
          <a-button @click="goBack">
            <template #icon>
              <ArrowLeftOutlined />
            </template>
            返回
          </a-button>
        </a-space>
        <div class="header-info">
          <h2>{{ interviewType }}</h2>
          <a-progress
            :percent="progress"
            :show-info="false"
            stroke-color="#1890ff"
          />
          <p>题目进度：{{ currentIndex + 1 }} / {{ questions.length }}</p>
        </div>
      </div>

      <!-- Loading状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin size="large" tip="面试正在准备中，请稍候...">
          <div style="padding: 50px; text-align: center">
            <p style="margin-top: 20px; color: #666">AI正在为您生成面试题目</p>
          </div>
        </a-spin>
      </div>

      <!-- 题目展示 -->
      <div v-else-if="currentQuestion" class="question-container">
        <a-card class="question-card">
          <div class="question-number">
            <a-tag color="blue">第 {{ currentIndex + 1 }} 题</a-tag>
          </div>
          <div class="question-content">
            <h3>{{ currentQuestion.questionName }}</h3>
          </div>

          <!-- 答案输入区域 -->
          <div class="answer-section">
            <a-textarea
              v-model:value="currentAnswer"
              placeholder="请输入您的答案，或点击语音输入按钮..."
              :rows="8"
              :maxlength="2000"
              show-count
            />
          </div>

          <!-- 操作按钮和语音输入按钮放在一起 -->
          <div class="action-buttons">
            <a-space size="middle">
              <!-- 语音输入按钮 -->
              <a-button
                :type="isRecording ? 'danger' : 'default'"
                @click="toggleRecording"
                :icon="isRecording ? h(AudioOutlined) : h(AudioMutedOutlined)"
                class="voice-btn"
              >
                {{ isRecording ? '停止录音' : '语音输入' }}
              </a-button>
              
              <span v-if="isRecording" class="recording-tip">
                <span class="recording-dot"></span>
                录音中...
              </span>
              
              <a-divider v-if="!isRecording" type="vertical" style="height: 32px; margin: 0 8px;" />
              
              <!-- 导航按钮 -->
              <a-button
                v-if="currentIndex > 0 && !isRecording"
                @click="previousQuestion"
              >
                上一题
              </a-button>
              <a-button
                v-if="currentIndex < questions.length - 1 && !isRecording"
                type="primary"
                @click="nextQuestion"
                :disabled="!currentAnswer.trim()"
                :loading="submitting"
              >
                下一题
              </a-button>
              <a-button
                v-if="currentIndex === questions.length - 1 && !isRecording"
                type="primary"
                @click="submitInterview"
                :disabled="!allQuestionsAnswered"
                :loading="submitting"
              >
                完成面试
              </a-button>
            </a-space>
          </div>
        </a-card>
      </div>

      <!-- 题目导航 -->
      <div class="question-nav">
        <h4>题目导航</h4>
        <a-space wrap>
          <a-button
            v-for="(q, index) in questions"
            :key="index"
            :type="index === currentIndex ? 'primary' : 'default'"
            @click="jumpToQuestion(index)"
            :class="{ 'answered': answers[index] }"
          >
            {{ index + 1 }}
            <CheckCircleOutlined v-if="answers[index]" style="margin-left: 4px" />
          </a-button>
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, h } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  AudioOutlined,
  AudioMutedOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons-vue'
import { addAnswer, generateInterviewQuestion } from '@/api/interviewReportController'

const router = useRouter()
const route = useRoute()

// 数据
const interviewType = ref<string>('')
const questions = ref<any[]>([])
const currentIndex = ref(0)
const answers = ref<string[]>([])
const currentAnswer = ref('')
const isRecording = ref(false)
const submitting = ref(false)
const loading = ref(true)

// 语音识别相关
let recognition: any = null

// 计算属性
const currentQuestion = computed(() => questions.value[currentIndex.value])
const progress = computed(() => ((currentIndex.value + 1) / questions.value.length) * 100)
const allQuestionsAnswered = computed(() => {
  // 保存当前答案到数组中再检查
  const tempAnswers = [...answers.value]
  tempAnswers[currentIndex.value] = currentAnswer.value
  return tempAnswers.every((answer) => answer && answer.trim())
})

// 初始化
onMounted(async () => {
  // 获取路由参数
  interviewType.value = route.query.interviewType as string
  const questionsStr = route.query.questions as string
  
  if (!interviewType.value) {
    message.error('参数错误')
    router.push('/interview')
    return
  }

  // 如果有questions参数，直接使用（兼容旧逻辑）
  if (questionsStr) {
    try {
      questions.value = JSON.parse(questionsStr)
      answers.value = new Array(questions.value.length).fill('')
      loading.value = false
    } catch (error) {
      message.error('数据解析失败')
      router.push('/interview')
      return
    }
  } else {
    // 否则，请求生成题目
    try {
      loading.value = true
      const res = await generateInterviewQuestion({
        interviewType: interviewType.value,
      })
      
      if (res.data.code === 0 && res.data.data) {
        questions.value = res.data.data
        answers.value = new Array(questions.value.length).fill('')
        loading.value = false
      } else {
        message.error('生成面试题目失败：' + res.data.message)
        router.push('/interview')
        return
      }
    } catch (error) {
      message.error('生成面试题目失败')
      console.error(error)
      router.push('/interview')
      return
    }
  }

  // 初始化语音识别
  initSpeechRecognition()
})

// 清理
onUnmounted(() => {
  if (recognition) {
    recognition.stop()
  }
})

// 初始化语音识别
const initSpeechRecognition = () => {
  // 检查浏览器是否支持语音识别
  const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition
  
  if (!SpeechRecognition) {
    console.warn('浏览器不支持语音识别')
    return
  }

  recognition = new SpeechRecognition()
  recognition.lang = 'zh-CN'
  recognition.continuous = true
  recognition.interimResults = true

  recognition.onresult = (event: any) => {
    let interimTranscript = ''
    let finalTranscript = ''

    for (let i = event.resultIndex; i < event.results.length; i++) {
      const transcript = event.results[i][0].transcript
      if (event.results[i].isFinal) {
        finalTranscript += transcript
      } else {
        interimTranscript += transcript
      }
    }

    if (finalTranscript) {
      currentAnswer.value += finalTranscript
    }
  }

  recognition.onerror = (event: any) => {
    console.error('语音识别错误:', event.error)
    if (event.error === 'no-speech') {
      message.warning('没有检测到语音，请重试')
    } else if (event.error === 'not-allowed') {
      message.error('未授权使用麦克风，请在浏览器设置中允许')
    }
    isRecording.value = false
  }

  recognition.onend = () => {
    isRecording.value = false
  }
}

// 切换录音状态
const toggleRecording = () => {
  if (!recognition) {
    message.warning('当前浏览器不支持语音识别，请使用Chrome或Edge浏览器')
    return
  }

  if (isRecording.value) {
    recognition.stop()
    isRecording.value = false
  } else {
    try {
      recognition.start()
      isRecording.value = true
      message.info('开始录音，请说话...')
    } catch (error) {
      console.error('启动录音失败:', error)
      message.error('启动录音失败')
    }
  }
}

// 保存当前答案
const saveCurrentAnswer = () => {
  answers.value[currentIndex.value] = currentAnswer.value
}

// 提交当前题目的答案到后端
const submitCurrentAnswer = async (isLast: boolean = false) => {
  const question = questions.value[currentIndex.value]
  const answer = currentAnswer.value

  try {
    const res = await addAnswer({
      id: question.id,
      userAnswer: answer,
      isLast: isLast,
    })

    if (res.data.code !== 0) {
      message.error(`提交答案失败：${res.data.message}`)
      return false
    }
    return true
  } catch (error) {
    message.error('提交答案失败')
    console.error(error)
    return false
  }
}

// 下一题
const nextQuestion = async () => {
  if (!currentAnswer.value.trim()) {
    message.warning('请先回答当前问题')
    return
  }
  
  saveCurrentAnswer()
  
  // 提交当前答案到后端
  submitting.value = true
  const success = await submitCurrentAnswer(false)
  submitting.value = false
  
  if (!success) {
    return
  }
  
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++
    currentAnswer.value = answers.value[currentIndex.value] || ''
  }
}

// 上一题
const previousQuestion = () => {
  saveCurrentAnswer()
  if (currentIndex.value > 0) {
    currentIndex.value--
    currentAnswer.value = answers.value[currentIndex.value] || ''
  }
}

// 跳转到指定题目
const jumpToQuestion = (index: number) => {
  saveCurrentAnswer()
  currentIndex.value = index
  currentAnswer.value = answers.value[index] || ''
}

// 提交面试
const submitInterview = async () => {
  // 检查是否所有题目都已回答
  if (!allQuestionsAnswered.value) {
    message.warning('请回答所有题目后再提交')
    return
  }

  Modal.confirm({
    title: '确认提交',
    content: '确定要完成面试并提交答案吗？提交后将无法修改。',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        submitting.value = true
        saveCurrentAnswer()

        // 提交最后一题的答案，标记为最后一题
        const success = await submitCurrentAnswer(true)
        
        if (!success) {
          return
        }

        message.success('面试完成，正在生成报告...')
        
        // 获取reportId并跳转到报告详情页面
        const reportId = questions.value[0]?.reportId
        if (reportId) {
          setTimeout(() => {
            router.push(`/interview/report/${reportId}`)
          }, 1500)
        } else {
          // 如果没有reportId，跳转到面试选择页面
          setTimeout(() => {
            router.push('/interview')
          }, 1500)
        }
      } catch (error) {
        message.error('提交失败')
        console.error(error)
      } finally {
        submitting.value = false
      }
    },
  })
}

// 返回
const goBack = () => {
  Modal.confirm({
    title: '确认退出',
    content: '退出后当前答题进度将丢失，确定要退出吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      router.push('/interview')
    },
  })
}
</script>

<style scoped>
.interview-answer-page {
  padding: 24px;
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 8%, #e2e8f0 20%, #cbd5e1 100%),
    radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.15) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.12) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(16, 185, 129, 0.08) 0%, transparent 50%);
  min-height: calc(100vh - 64px);
}

:deep(.ant-card) {
  max-width: 900px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #fff;
  border-radius: 16px;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.header-info {
  margin-top: 16px;
  background: linear-gradient(135deg, #60a5fa 0%, #a78bfa 100%);
  padding: 24px;
  border-radius: 12px;
  color: #fff;
}


.header-info h2 {
  font-size: 28px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 16px;
}

.header-info p {
  margin-top: 8px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
}

:deep(.ant-progress-line) {
  margin: 16px 0;
}

:deep(.ant-progress-bg) {
  background: linear-gradient(90deg, #ffffff 0%, #e0e7ff 30%, #a78bfa 100%);
  box-shadow: 0 0 8px rgba(167, 139, 250, 0.6);
  height: 10px;
  border-radius: 10px;
}

.question-container {
  margin-bottom: 24px;
}

.question-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  overflow: hidden;
}

.question-number {
  margin-bottom: 16px;
}

:deep(.ant-tag) {
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 6px;
}

.question-content {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%);
  border-radius: 12px;
  margin-bottom: 24px;
  border-left: 4px solid #3b82f6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.question-content h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  line-height: 1.8;
}

.answer-section {
  margin-bottom: 20px;
}

:deep(.ant-input) {
  border-radius: 8px;
}

:deep(textarea.ant-input) {
  border: 2px solid #e8edf2;
  transition: all 0.3s;
}

:deep(textarea.ant-input:focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.voice-btn {
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
}

.recording-tip {
  margin-left: 12px;
  color: #ff4d4f;
  font-weight: 500;
  font-size: 14px;
}

.recording-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background: #ff4d4f;
  border-radius: 50%;
  margin-right: 8px;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
}

.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px 0;
}

.action-buttons .ant-btn {
  border-radius: 8px;
  height: 40px;
  min-width: 100px;
  font-weight: 500;
}

.action-buttons .ant-btn-primary {
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
  border: none;
}

.action-buttons .ant-btn-primary:hover:not(:disabled) {
  background: linear-gradient(135deg, #8b5cf6 0%, #10b981 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.question-nav {
  margin-top: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.question-nav h4 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.question-nav .ant-btn {
  border-radius: 8px;
  min-width: 44px;
  height: 44px;
  font-weight: 500;
  transition: all 0.3s;
}

.question-nav .ant-btn-primary {
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
  border: none;
}

.answered {
  border-color: #52c41a;
  color: #52c41a;
  background: #f6ffed;
}

.answered:hover {
  border-color: #52c41a !important;
  color: #52c41a !important;
}

@media (max-width: 768px) {
  .interview-answer-page {
    padding: 16px;
  }
  
  .header-info h2 {
    font-size: 24px;
  }
  
  .question-content h3 {
    font-size: 16px;
  }
}
</style>

